import NetAdapter from "../../adpapter/NetAdapter";
import { AlertManager } from "../../alert/AlertManager";
import { MVC } from "../../framework/MVC";
import { Time } from "../../framework/Time";
import GlobalData from "../../GlobalData";
import DeviceManager from "../../manager/DeviceManager";
import { GameVoManager } from "../../manager/GameVoManager";
import { Util } from "../../utils/Util";

const { ccclass, property } = cc._decorator;

@ccclass
export default class FuliView extends MVC.BaseView {


    @property(cc.Label)
    douyinCount: cc.Label = null;

    @property(cc.Label)
    kuaishouCount: cc.Label = null;

    @property(cc.Label)
    UID: cc.Label = null;

    @property(cc.Label)
    ToUID: cc.Label = null;


    @property(cc.Node)
    yongjingBox: cc.Node = null;

    @property(cc.Label)
    yongjing: cc.Label = null;


    @property(cc.Node)
    creatTime: cc.Node = null;

    @property(cc.EditBox)
    dailiInput: cc.EditBox = null;

    @property({
        displayName: "后面添加的功能界面",
        type: cc.Node
    })
    addNode: cc.Node = null;


    @property(cc.Node)
    adAppDouyin: cc.Node = null;

    @property(cc.Node)
    adAppKuaishou: cc.Node = null;

    @property(cc.Node)
    app_bg: cc.Node = null;

    @property(cc.Node)
    mingame_bg: cc.Node = null;

    maxCount = 10;
    reward_power = 8;
    reward_diamond = 50;
    miniGameMaxCount = 5;//福利抖音小游戏/快手小游戏观看广告限制
    protected changeListener(enable: boolean): void {
    }

    public onOpen(args?: any): void {

        // this.app_bg.active = false;
        // this.mingame_bg.active = true;

        this.appAdOrderByMiniGame();
        // 确保 agent_uid 是字符串类型
        if (GlobalData.inst.agent_uid != null) {
            GlobalData.inst.agent_uid = String(GlobalData.inst.agent_uid);
            if (GlobalData.inst.agent_uid != "0" && GlobalData.inst.agent_uid != "" && GlobalData.inst.agent_uid.indexOf("uid") !== -1) {
                GlobalData.inst.agent_uid = GlobalData.inst.agent_uid.replace(/uid/g, "");
            }
        }
        //创建时间
        let time = Util.convertTimestampToDateTime(GlobalData.inst.create_time);
        this.creatTime.getComponent(cc.Label).string = '创建时间：' + time;
        // 绑定代理
        this.dailiInput.string = "";
        if (GlobalData.inst.agent_uid && GlobalData.inst.agent_uid != "0") {
            this.dailiInput.string = GlobalData.inst.agent_uid + "";
            this.dailiInput.enabled = false;
        }

        let date = true ? new Date() : new Date(Time.serverTimeMs);
        let curday = date.getDate();
        this.UID.string = GlobalData.inst.uid;
        this.ToUID.string = GlobalData.inst.agent_uid == "0" || GlobalData.inst.agent_uid == "" ? "暂未绑定代理" : GlobalData.inst.agent_uid;
        if (curday != GameVoManager.getInstance.myUserVo.day) {
            console.log("重置福利每日领取次数");
            GameVoManager.getInstance.myUserVo.fuliGetDouyinCount = 0;
            GameVoManager.getInstance.myUserVo.fuliGetKuaishouCount = 0;
            GameVoManager.getInstance.myUserVo.fuliInter = false;
        }
        this.updateCount();
        this.yongjingBox.active = false;

    }

    onDaliConfirm() {
        if (GlobalData.inst.agent_uid != "" && GlobalData.inst.agent_uid != "0") {
            AlertManager.showNormalTips("你已经绑定过了！");
        } else {
            let agent_uid = this.dailiInput.string;
            if (agent_uid == "") {
                AlertManager.showNormalTips("请输入代理ID");
                return;
            }
            NetAdapter.userUpdateDaili({ agent_uid: agent_uid })
                .then((res) => {
                    Util.logExt(res, "绑定成功");
                    console.log(res);
                    GlobalData.inst.agent_uid = agent_uid;
                    this.ToUID.string = GlobalData.inst.agent_uid == "0" || GlobalData.inst.agent_uid == "" ? "暂未绑定代理" : GlobalData.inst.agent_uid;
                    AlertManager.showNormalTips("绑定成功！");

                })
                .catch((err) => {
                    Util.logExt(err, "绑定失败");
                    // AlertManager.showNormalTips("绑定失败");
                });
        }
    }
    updateCount() {
        if(GameVoManager.getInstance.myUserVo.fuliGetDouyinCount > this.miniGameMaxCount)
        {
            GameVoManager.getInstance.myUserVo.fuliGetDouyinCount = this.miniGameMaxCount
        }
        if(GameVoManager.getInstance.myUserVo.fuliGetKuaishouCount > this.miniGameMaxCount)
        {
            GameVoManager.getInstance.myUserVo.fuliGetKuaishouCount = this.miniGameMaxCount
        }
        this.douyinCount.string = `${GameVoManager.getInstance.myUserVo.fuliGetDouyinCount}/${this.miniGameMaxCount}`;
        this.kuaishouCount.string = `${GameVoManager.getInstance.myUserVo.fuliGetKuaishouCount}/${this.miniGameMaxCount}`;
    }
    onClockOK() {
        this.yongjingBox.active = false;
    }
    onClickKefu() {
        DeviceManager.inst.openBower("https://work.weixin.qq.com/kfid/kfc54e166ca9cd39856");
    }
    onCkickAppToDouyin() {
        if (!Util.isDouyinGame() && !Util.isKuaishouGame() && (GlobalData.inst.agent_uid == "" || GlobalData.inst.agent_uid == "0")) {
            AlertManager.showNormalTips("绑定代理后才可通过视频获取奖励");
            return;
        }
        // 跳转抖音小游戏
        const appId = 'ttd2baa4074d898fda02';
        // const douyinLink =`snssdk1128://microgame?app_id=${appId}&uid=${GlobalData.inst.uid}`
        const params = { uid: GlobalData.inst.uid };
        // 编码参数
        const query = encodeURIComponent(JSON.stringify(params));
        const douyinLink =`snssdk1128://microgame?app_id=${appId}&query=${query}`
        // 判断平台
        if (cc.sys.isNative) {
            if (cc.sys.os === cc.sys.OS_ANDROID) {
                // Android 使用 Intent 跳转
                jsb.reflection.callStaticMethod("com/jingyingxiaobing/blueclient/AppActivity", "openDouyinLink", "(Ljava/lang/String;)V", douyinLink);
            } else if (cc.sys.os === cc.sys.OS_IOS) {
                // iOS 跳转
                jsb.reflection.callStaticMethod("AppController", "openDouyinLink:", douyinLink);
            }
        } else {
            // Web 端直接跳转（仅调试用）
            window.open(douyinLink, "_blank");
        }
    }

    onCkickAppToKuaishou() {
        if (!Util.isDouyinGame() && !Util.isKuaishouGame() && (GlobalData.inst.agent_uid == "" || GlobalData.inst.agent_uid == "0")) {
            AlertManager.showNormalTips("绑定代理后才可通过视频获取奖励");
            return;
        }
        // 跳转快手小游戏
        const appId = 'ks664280947379365173';
        // const path = ``;
        //小程序的跳转方式
        // const kuaishouLink =`kwai://miniapp?appId=${appId}&path=${path}`
        //小游戏开户链接
        const kuaishouLink =`kwai://sogame/launch?appId=${appId}&from=dsp_kuaishou_default_w&uid=${GlobalData.inst.uid}`

        // 判断平台
        if (cc.sys.isNative) {
            if (cc.sys.os === cc.sys.OS_ANDROID) {
                // Android 使用 Intent 跳转
                jsb.reflection.callStaticMethod("com/jingyingxiaobing/blueclient/AppActivity", "openKuaishouLink", "(Ljava/lang/String;)V", kuaishouLink);
            } else if (cc.sys.os === cc.sys.OS_IOS) {
                // iOS 跳转
                jsb.reflection.callStaticMethod("AppController", "openKuaishouLink:", kuaishouLink);
            }
        } else {
            // Web 端直接跳转（仅调试用）
            window.open(kuaishouLink, "_blank");
        }
    }
    //小游戏看广告生成订单
    miniGameAdOrder() {
        if (Util.isDouyinGame() || Util.isKuaishouGame()) {
            console.log("小游戏看广告生成订单")
            NetAdapter.advOrderDev({
                uid: GlobalData.inst.uid,
            }).then(res => {
                Util.logExt(res, "advOrderDev:");
            }).catch(err => {
                Util.logExt(err, "advOrderDev err");
            });
        }
    }
    //抖音小游戏/快手小游戏看广告次数
    appAdOrderByMiniGame() {
        if (Util.isDouyinGame() || Util.isKuaishouGame()) {
         
        }else
        {
            let DouyinCount =0;
            let KuaishouCount =0;
            NetAdapter.appAdOrderByMiniGame({
            })
              .then((res: any) => {
                let list: any = res;
                list.forEach(itemInfo => {
                    if(itemInfo.user_type ==5)
                    {
                        DouyinCount =DouyinCount +itemInfo.adv_viewed_num
                    }else  if(itemInfo.user_type ==8)
                    {
                        KuaishouCount =KuaishouCount +itemInfo.adv_viewed_num
                    }
                  });
                  GameVoManager.getInstance.myUserVo.fuliGetDouyinCount =DouyinCount;
                  GameVoManager.getInstance.myUserVo.fuliGetKuaishouCount =KuaishouCount;
                  this.updateCount();
              })
              .catch((err) => {});
          }
        }

}